﻿using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Threading;


namespace Wayloop.Blog.Core.Services.Impl
{
    public class EmailNotificationService : INotificationService
    {
        /// <summary>
        /// Gets or sets the <see cref="IConfigurationService"/> implementation.
        /// </summary>
        /// <value>The <see cref="IConfigurationService"/> implementation.</value>
        public IConfigurationService ConfigurationService { get; protected set; }


        /// <summary>
        /// Initializes a new instance of the <see cref="EmailNotificationService"/> class.
        /// </summary>
        /// <param name="configurationService">The <see cref="IConfigurationService"/> implementation.</param>
        public EmailNotificationService(IConfigurationService configurationService)
        {
            ConfigurationService = configurationService;
        }


        public virtual void SendNotification(string subject, string message)
        {
            SendEmail(ConfigurationService.AuthorEmailAddress, subject, message);
        }


        protected virtual void SendEmail(string recipient, string subject, string body)
        {
            SendEmail(new[] { recipient }, subject, body);
        }


        protected virtual void SendEmail(IEnumerable<string> recipients, string subject, string body)
        {
            var smtpClient = new SmtpClient();
            var message = new MailMessage {
                Subject = subject,
                SubjectEncoding = Encoding.UTF8,
                Body = body,
            };

            foreach (string recipient in recipients) {
                message.To.Add(new MailAddress(recipient));
            }

            ThreadPool.QueueUserWorkItem(callback => smtpClient.Send(message));
        }
    }
}